<?php
include('../services/config.php');
include('simple_html_dom.php');


$conn = pg_connect ("host=".DB_HOST." dbname=".DB_NAME." user=".DB_USER." password=".DB_PASSWORD);
define("MAPS_HOST", "maps.google.com");
define("KEY", "abcdefg");
$googleGeocodeBase = "http://maps.google.com/maps/api/geocode/json?language=es&sensor=false";

$url="http://www.juntadeandalucia.es/contratacion/ContractNoticeSearch.action?seeAll=Y&sortCriteria=1&order=asc&hitsPerPage=20";
$html = file_get_dom($url);

foreach($html->find('div.modulo_contenido') as $cont) {
    $a=$cont->find('a');
    if(strpos($a[0]->href, "ContractNoticeDetail")!== false) {
        $url=$a[0]->href;
        /*$perfil_contratante_nombre = html_entity_decode(trim(str_replace("Perfil de contratante:&nbsp;","",$cont->children[1]->plaintext)),ENT_COMPAT,"UTF-8");
        $estado=html_entity_decode( trim( 
            str_replace("Estado:&nbsp;","",$cont->children[2]->plaintext)),ENT_COMPAT,"UTF-8");
        echo($estado."\n");
        */
        $html2 = file_get_dom("http://www.juntadeandalucia.es".$url);
        $lic=$html2->find('div#detalle');
        $lic=$lic[0];
        $arr=$lic->find('p');
        $i=0;
        foreach($arr as $p) {
            if(strpos(cleanText($p->plaintext), "Referencia de publicación:")!== false) {
                $ref_publicacion= removeTextAndClean($p->plaintext,"Referencia de publicación:");
            }
            if(strpos(cleanText($p->plaintext), "Fecha y hora de publicación:")!== false) {
                $fecha_publicacion= removeTextAndClean($p->plaintext,"Fecha y hora de publicación:");
            }
            if(strpos(cleanText($p->plaintext), "Estado:")!== false) {
                $estado= removeTextAndClean($p->plaintext,"Estado:");
            }    
            if(strpos(cleanText($p->plaintext), "Perfil de contratante:")!== false) {
                $perfil_contratante= removeTextAndClean($p->plaintext,"Perfil de contratante:");
            }  
            if(strpos(cleanText($p->plaintext), "Órgano convocante:")!== false) {
                $tipo_licitacion= removeTextAndClean($p->plaintext,"Órgano convocante:");
            }
            if(strpos(cleanText($p->plaintext), "Denominación del contrato:")!== false) {
                $titulo= removeTextAndClean($p->plaintext,"Denominación del contrato:");
            }   
            if(strpos(cleanText($p->plaintext), "Número de expediente:")!== false) {
                $expediente= removeTextAndClean($p->plaintext,"Número de expediente:");
            }   
            if(strpos(cleanText($p->plaintext), "B.Tramitación, procedimiento y forma de adjudicación")!== false) {
                $tipo_procedimiento= removeTextAndClean($arr[$i+1]->plaintext,"");
            }
            if(strpos(cleanText($p->plaintext), "Lugar")!== false) {
                $location= removeTextAndClean($p->plaintext,"Lugar de presentación:");
                $request_url = $googleGeocodeBase . "&address=" . urlencode($location.",spain");
                $resp = json_decode(file_get_contents($request_url));
                $cp=$resp->results[0]->address_components[0]->long_name;
                $poblacion=$resp->results[0]->address_components[1]->long_name;
                $direccion=$location;
                $provincia=$resp->results[0]->address_components[2]->long_name;
                $comunidad_autonoma=$resp->results[0]->address_components[3]->long_name;
                $lat=$resp->results[0]->geometry->location->lat;
                $lon=$resp->results[0]->geometry->location->lng;             			
            }            
            
            if(strpos(cleanText($p->plaintext), "Importe total:")!== false) {
                $importe= removeTextAndClean($p->plaintext,"Importe total:");
                $importe =str_replace("€","",$importe);
                $importe =str_replace(".","",$importe);
                $importe =str_replace(",",".",$importe);
            }            
            $i++;                                                                  
        }    
        
        //Primero comprobar si el perfil contratante ya esta en la base de datos
        $sql="SELECT id from perfil_contratante WHERE nombre='$perfil_contratante' LIMIT 1";
        $res=pg_fetch_all(pg_query($conn, $sql)); 
        if(!$res) {
            //No esta en la BBDD, importar de nuevo
            $sql="INSERT INTO perfil_contratante(nombre) VALUES('$perfil_contratante')";
            pg_query($conn, $sql);
            $sql = "SELECT currval('perfil_contratante_id_seq') AS last_value";
    	    $result=pg_query($conn, $sql);
    	    $res=pg_fetch_assoc($result);
    	    $perfil_contratante_id=$res['last_value'];
		} else {
		    //Ya esta coger el ID
		    $perfil_contratante_id=$res[0]['id'];
		}        
        
    }
    
    
    
}

function cleanText($text) {
    return html_entity_decode(trim(utf8_encode($text)),ENT_COMPAT,"UTF-8");
}

function removeTextAndClean($text,$toRemove) {

    $line = ereg_replace("[\n\r]", "\t", $text);
    $line = ereg_replace("\t\t+", "\n", $line);
    $line = trim(str_replace($toRemove,"",cleanText($line)));
    return $line;
    
}


function normalize ($string) {
    $table = array(
        'Š'=>'S', 'š'=>'s', 'Đ'=>'Dj', 'đ'=>'dj', 'Ž'=>'Z', 'ž'=>'z', 'Č'=>'C', 'č'=>'c', 'Ć'=>'C', 'ć'=>'c',
        'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A', 'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E',
        'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I', 'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
        'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss',
        'à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e',
        'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i', 'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o',
        'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u', 'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
        'ÿ'=>'y', 'Ŕ'=>'R', 'ŕ'=>'r',
    );
    
    return strtr($string, $table);
}



?>